//
// Created by bd on 2019/11/12.
//

#include <iostream>
#include <event2/event.h>
#include <csignal>

using namespace std;

static timeval tv1 = {1, 0};

static void timer1_cb(int socket, short which, void *arg)
{
    cout << __FUNCTION__ << endl;
    // 再次添加事件
    auto ev = reinterpret_cast<event *>(arg);
    if (!evtimer_pending(ev, &tv1)) {
        evtimer_del(ev);
        evtimer_add(ev, &tv1);
    }
}

static void timer2_cb(int socket, short which, void *arg)
{
    cout << __FUNCTION__ << endl;
}


int main()
{
    // 忽略管道信号，发送数据给已关闭的socket
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return 1;

    auto base = event_base_new();
    if (!base) {
        cerr << "event base new failed, exit." << endl;
        return 1;
    }

    // 方式1，使用evtimer_系列接口
    // 定时器事件，非持久,只进入回调函数一次
    auto ev1 = evtimer_new(base, timer1_cb, event_self_cbarg());
    if (!ev1) {
        event_base_free(base);
        cerr << "evtimer new failed, exit." << endl;
        return 1;
    }
    evtimer_add(ev1, &tv1);

    // 方式2，使用event_系列接口实现timer, 并持久化
    timeval tv2;
    tv2.tv_sec = 1;
    tv2.tv_usec = 400000;
    auto ev2 = event_new(base,-1, EV_PERSIST, timer2_cb, nullptr);
    if (!ev2) {
        event_base_free(base);
        cerr << "event new failed, exit." << endl;
        return 1;
    }
    evtimer_add(ev2, &tv2);

    event_base_dispatch(base);

    evtimer_del(ev1);
    evtimer_del(ev2);
    event_base_free(base);

    return 0;
}